import pandas as pd
import numpy as np


# 逆向指标标准化
def normalization1(data):
    _range = np.max(data) - np.min(data)
    return (data - np.min(data)) / _range


# 正向指标标准化
def normalization2(data):
    _range = np.max(data) - np.min(data)
    return (np.max(data) - data) / _range


# 熵权法计算权重
def entropyWeight(data):
    P = np.array(data)
    # 计算熵值
    E = np.nansum(-P * np.log(P) / np.log(len(data)), axis=0)
    # 计算权系数
    return (1 - E) / (1 - E).sum()


def topsis(data, weight=None):
    # 权重
    weight = entropyWeight(data) if weight is None else np.array(weight)

    # 最优最劣方案
    Z = pd.DataFrame([(data * weight.T).min(), (data * weight.T).max()], index=['负理想解', '正理想解'])
    # Z = pd.DataFrame([data.min(), data.max()], index=['负理想解', '正理想解'])

    # 距离
    Result = data.copy()
    # Result['正理想解'] = np.sqrt(((data - Z.loc['正理想解']) ** 2 * weight).sum(axis=1))
    # Result['负理想解'] = np.sqrt(((data - Z.loc['负理想解']) ** 2 * weight).sum(axis=1))
    Result['正理想解'] = np.sqrt(((weight * data - Z.loc['正理想解']) ** 2).sum(axis=1))
    Result['负理想解'] = np.sqrt(((weight * data - Z.loc['负理想解']) ** 2).sum(axis=1))

    # 综合得分指数
    Result['综合得分指数'] = Result['负理想解'] / (Result['负理想解'] + Result['正理想解'])
    Result['排序'] = Result.rank(ascending=False)['综合得分指数']

    return Result, Z, weight


import pandas as pd
import numpy as np

# ...（这里是您提供的所有函数）...

if __name__ == '__main__':
    # 加载数据
    data = pd.read_csv('排名数据.csv')  # 确保文件名和路径正确

    # 选择需要的列
    columns = ['评论数量', '平均评论长度', '平均play_count', '平均rating', '平均Sentiment']
    data_for_ranking = data[columns]

    # 标准化数据
    for col in columns:
        data_for_ranking[col] = normalization1(data_for_ranking[col])

    # 计算TOPSIS评分
    [result, z1, weight] = topsis(data_for_ranking)

    # 合并歌曲标号和TOPSIS评分
    final_result = pd.DataFrame()
    final_result['歌曲标号'] = data['歌曲标号']
    final_result['排名'] = result['排序']
    final_result['评分'] = result['综合得分指数']

    # 输出每个指标的权重值
    print("各指标权重：")
    for col, w in zip(columns, weight):
        print(f"{col}: {w}")

    # 根据评分对歌曲进行排序
    final_result.sort_values(by='评分', ascending=False, inplace=True)

    # 重置索引
    final_result.reset_index(drop=True, inplace=True)

    # 保存到CSV
    final_result.to_csv('music_rankings.csv', index=False, encoding='utf_8_sig')
